package by.bsu.rfe.belianko.euniversity.controller.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.ErrorMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.model.Student;

/**
 * Checks whether the student in session.
 * 
 * @author Vitali_Belianko
 * 
 */
public class StudentSessionFilter implements Filter {
	private static final String DO_FILTER = "Do Filter!";
	private static final String PATTERN = "pattern";
	private static final String STUDENT_ATTR = "student";
	private static final String WEB_INF_PAGES = "/WEB-INF/pages/";
	private static final String ERROR_MESSAGE = "errorMessage";
	private static final Logger LOGGER = Logger.getLogger(StudentSessionFilter.class);
	private String pattern;

	/**
	 * Checks whether the student in session.
	 * 
	 * @param request
	 *            - ServletRequest
	 * @param response
	 *            - ServletResponse
	 * @param chain
	 *            - FilterChain
	 * @throws ServletException
	 * @throws IOException
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		Student studentAttribute = (Student) req.getSession().getAttribute(STUDENT_ATTR);
		String queryString = req.getQueryString();
		if (queryString != null) {
			if (queryString.matches(pattern)) {

				if (studentAttribute != null) {
					chain.doFilter(request, response);
				} else {
					LOGGER.debug(DO_FILTER);
					req.setAttribute(ERROR_MESSAGE, ErrorMessages.NOT_SIGNED_IN);
					RequestDispatcher dispatcher = req.getRequestDispatcher(WEB_INF_PAGES + PageNames.LOGIN_PAGE);
					dispatcher.forward(request, response);
				}
			} else {
				chain.doFilter(request, response);
			}
		} else {

			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.pattern = filterConfig.getInitParameter(PATTERN);
	}

	@Override
	public void destroy() {

	}

}
